var yuming = 'http://activity.didadiandan.com';//服务器地址
var inputIdArr = ['xinyun','three','two','one'];
var html = "";
var value = 0;//人数
var imgUrl = "http://frontend.didadiandan.com/lottery-draw/img/timg.jpg";
var optionValue = "";
var drawInterval = "";
var personToPicture = "";//扫描二维码上墙定时器
var pubres = [];
var res = [];
var isDraw = false;//是否抽过奖
var initArr = [{name:'???',image:imgUrl}];
var index = 0;//不能点两次
var userLists;//所有的参与人
localStorage.storageArr = JSON.stringify([{"value":"5"},{"value":"5"},{"value":"5"},{"value":"1"},{"value":"1"}]);
if(!localStorage.storageArr) {
  $('.writePriceNum').show();
  $('.container').hide();
}else {
  optionValue = "all";
  $('.writePriceNum').hide();
  $('.container').show();
}

//
$('#enterDraw').click(function () {
  var tempArr = [];
  var totalInput = 0;
  var is_check = $('#sendSms').is(':checked');
  for (var i = 0; i < inputIdArr.length; i++) {
    tempArr.push({
      value:$('#'+inputIdArr[i]).val(),
    })
  }
  for (var i = 0; i < tempArr.length; i++) {
    totalInput += Number(tempArr[i].value);
    if(!tempArr[i].value) {
      fish.notify("请填写完整的抽奖人数！");
      return false;
    }
    if(Number(tempArr[i].value) <= 0) {
      fish.notify("抽奖人数必须为正整数！");
      return false;
    }
  }
  localStorage.storageArr = JSON.stringify(tempArr);
  localStorage.sendSms = is_check;
  $('.writePriceNum').hide();
  $('.container').show();
  optionValue = "all";
  renderUserLists();//重置一次
});
//
// 初始话渲染
renderUserLists("out");
personToPicture = setInterval(function () {
  // console.log(1);
    renderUserLists();
},10*1000);

$('#select').on('change',function () {
  html = "";
  var storageArr;
  if(localStorage.storageArr) {
    storageArr = JSON.parse(localStorage.storageArr);
  }
  // console.log(this.options[this.options.selectedIndex].value);
  optionValue = this.options[this.options.selectedIndex].value;
  if(optionValue == "all") {
    personToPicture = setInterval(function () {
      // console.log(1);
        renderUserLists();
    },10*1000);
  }else {
    clearInterval(personToPicture);
  }
  switch (optionValue) {
    case '四等奖':
      value = Number(storageArr[0].value);
      $('.productImg img').attr({'src':'./img/pic1.jpg'});
      $('.productDesc p').html('四等奖：星驰科技 力博得牙刷套装 价值499');
      break;
    case '三等奖':
      value = Number(storageArr[1].value);
      $('.productImg img').attr({'src':'./img/pic21.jpg'});
      $('.productDesc p').html('三等奖：施坦威钢琴 定制茶具 价值880');
      break;
    case '二等奖':
      value = Number(storageArr[2].value);
      $('.productImg img').attr({'src':'./img/pic22.jpg'});
      $('.productDesc p').html('二等奖：星巢珠宝 金箔笔礼盒 价值1280');
      break;
    case '一等奖':
      value = Number(storageArr[3].value);
      $('.productImg img').attr({'src':'./img/pic31.jpg'});
      $('.productDesc p').html('一等奖：嘉亿传媒 汉麻世家空调毯 价值4800');
      break;
    case '备用':
      value = Number(storageArr[4].value);
      $('.productImg img').attr({'src':'./img/pic.jpg'});
      $('.productDesc p').html('');
      break;
    default:
      // value = userLists.length;
      $('.productImg img').attr({'src':'./img/pic.jpg'});
      $('.productDesc p').html('');
      renderHtml(userLists.length,html,'userLists');
      return false;
  };
  checkHowToRender();
});


$('#startStop').click(function () {
  if(optionValue == "all") {
    fish.notify("请选择抽奖等级！");
    return false;
  }
  if(isDraw) {
    fish.notify("您已经抽过该奖项！");
    return false;
  }
  if(index == 0){ index = 1 } else { return false };
  var content = $(this).html();
  if(content == "开始") {
    var self = this;
    fish.smallModal("是否开始"+optionValue+"的抽奖？",function () {
      $('#select').attr({"disabled":"disabled"});
      drawPrice();
      $(self).html("停止");
    });
    index = 0;
  }else {
    $('#select').removeAttr("disabled");
    var self = this;
    // $.post(yuming+'/web/draw/start',{levelName:optionValue,num:value,needSendSms:localStorage.sendSms},function (data) {
    $.post(yuming+'/web/draw/start',{levelName:optionValue,num:value,needSendSms:false},function (data) {
        clearInterval(drawInterval);
        if(data.code == 100) {
            isDraw = true;
            res = data.object;
            // console.log(res);
            html = "";
            renderHtml(value,html,'res');
        }else {
          fish.notify("抽奖无效："+data.message);
          renderHtml(value,html,'pubres');
        }
        $(self).html("开始");
        index = 0;
    },"json");
  }
})

$('#clear').click(function () {
  if(optionValue == "all") {
    fish.notify("这是参与人，您不能重置！");
    return false;
  }
  fish.smallModal("您确定要重置"+optionValue+"嘛？",function () {
    $.post(yuming+'/web/draw/clear',{levelName:optionValue},function (data) {
        if(data.code == 100) {
            isDraw = false;
            renderHtml(value,html,'pubres');
            // fish.notify("清除"+optionValue+"成功！");
        }else {
          fish.notify(data.message);
        }
    },"json");
  });
})
$('#reset').click(function () {
  fish.smallModal("您确定要重置所有抽奖嘛？",function () {
    $.post(yuming+'/web/draw/clear',{},function (data) {
        localStorage.clear();
        window.location.reload();
        // if(data.code == 100) {
        //     fish.notify("重置所有抽奖成功",function () {
        //       var href = window.location.href;
        //       //在备份页面要清除localStorage
        //       if(href.indexOf("backups") != -1) {
        //         localStorage.clear();
        //       }
        //       window.location.reload();
        //     })
        // }else {
        //   fish.notify(data.message);
        // }
    },"json");
  })
})

function renderUserLists() {
  var storageArr;
  if(localStorage.storageArr) {
    storageArr = JSON.parse(localStorage.storageArr);
  }
  $.post(yuming+'/web/draw/list',{},function (data) {
      if(data.code == 100) {
          var inner = $('.container').is(":visible");
          if(!inner || (inner && optionValue == "all")) {
            userLists = data.object;
            // value = userLists.length;
            $('#allPerson').html('（共'+userLists.length+'人参与）');
            /*渲染初始设置界面*/
            if(!storageArr) return false;
            $('#select option').each(function (i,n) {
              // console.log(i,n);
              var content = ['参与人  '+userLists.length+'人','四等奖  '+storageArr[0].value+'人','三等奖  '+storageArr[1].value+'人','二等奖  '+storageArr[2].value+'人','一等奖  '+storageArr[3].value+'人','备用  '+storageArr[4].value+'人'];
              $(n).html(content[i])
            });
            renderHtml(userLists.length,html,'userLists');
          }
          // checkHowToRender();
      }else {
        fish.notify(data.message);
      }
  },"json");
}

function renderHtml(value,html,type) {
  html = "";
  if(type == 'userLists') {//渲染全部用户信息
    for (var i = 0; i < userLists.length; i++) {
      html +=
      '<div>'+
        '<img src='+(userLists[i].image || imgUrl)+' alt="">'+
        '<span title='+userLists[i].name+'>'+userLists[i].name+'</span>'+
      '</div>'
    }
  }else if(type == 'pubres') {
    for (var i = 0; i < value; i++) {
      html +=
      '<div>'+
        '<img src='+initArr[0].image+' alt="">'+
        '<span>'+initArr[0].name+'</span>'+
      '</div>'
    }
  }else {
    for (var i = 0; i < value; i++) {
      // if(!res[i].hasOwnProperty('image')) {
      //   res[i].image = imgUrl;
      // }
      html +=
      '<div>'+
        '<img src='+(res[i].image || imgUrl)+' alt="">'+
        '<span>'+res[i].name+'</span>'+
      '</div>'
    }
  }
  $('.leftul li ').html(html);
}

function drawPrice() {
  var randomMax = userLists.length;
  drawInterval = setInterval(function () {
    html = "";
    for (var i = 0; i < value; i++) {
      var randomPerson = userLists[Math.floor(Math.random()*randomMax)];
      html +=
      '<div>'+
        '<img src='+(randomPerson.image || imgUrl)+' alt="">'+
        '<span>'+randomPerson.name+'</span>'+
      '</div>'
    }
    $('.leftul li').html(html);
  },100)
}

function checkHowToRender() {
  $.post(yuming+'/web/draw/view',{levelName:optionValue},function (data) {
      if(data.code == 100) {
          res = data.object;
          if(res.length == 0) {
            isDraw = false;
            renderHtml(value,html,'pubres');
          }else {
            for (var i = 0; i < res.length; i++) {
              res[i].name = res[i].weixinName
            }
            // console.log(res);
            isDraw = true;
            html = "";
            renderHtml(res.length,html,'res');
          }
      }else {
        fish.notify(data.message);
      }
  },"json");
}
